<?php
namespace app\api\controller;
use think\Controller;
use think\Db;
/*
 * 此文件用于验证短信服务API接口，供开发时参考
 * 执行验证前请确保文件为utf-8编码，并替换相应参数为您自己的信息，并取消相关调用的注释
 * 建议验证前先执行Test.php验证PHP环境
 * 短信接口调用错误码参考地址：https://help.aliyun.com/knowledge_detail/57717.html?spm=5176.doc55451.2.9.i8NYgs
 * 2017/12/29
 */

class Sms extends Controller {
    // 发送验证码
    /*
     * @return array
     * ['Message'] ['RequestId'] ['BizId'] ['Code']
     */
    private function sendSms($phone, $code,$TemplateCode='SMS_171850168') {
        //set_time_limit(0); // 防止脚本超时，仅用于测试使用，生产环境请按实际情况设置
        $params = [];
        // *** 需用户填写部分 ***

        // fixme 必填: 请参阅 https://ak-console.aliyun.com/ 取得您的AK信息
        $accessKeyId     = config('aliyun.accessKeyId');
        $accessKeySecret = config('aliyun.accessKeySecret');

        // fixme 必填: 短信接收号码
        $params["PhoneNumbers"] = $phone;

        // fixme 必填: 短信签名，应严格按"签名名称"填写，请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/sign
        $params["SignName"] = config('aliyun.signName');

        // fixme 必填: 短信模板Code，应严格按"模板CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template
        $params["TemplateCode"] = $TemplateCode;

        // fixme 可选: 设置模板参数, 假如模板中存在变量需要替换则为必填项
        $params['TemplateParam'] = [
            'code'    => $code,
            'product' => 'code',
        ];

        // fixme 可选: 设置发送短信流水号
        $params['OutId'] = "12345";

        // fixme 可选: 上行短信扩展码, 扩展码字段控制在7位或以下，无特殊需求用户请忽略此字段
        $params['SmsUpExtendCode'] = "1234567";


        // *** 需用户填写部分结束, 以下代码若无必要无需更改 ***
        if (!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
            $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
        }

        // 初始化SignatureHelper实例用于设置参数，签名以及发送请求
        $helper = new SignatureHelper();

        // 此处可能会抛出异常，注意catch
        $arr     = [
            "RegionId" => "cn-hangzhou",
            "Action"   => "SendSms",
            "Version"  => "2017-05-25",
        ];
        $content = $helper->request($accessKeyId, $accessKeySecret, "dysmsapi.aliyuncs.com", array_merge($params, $arr));
        if (is_object($content)) {
            $content = (array)$content;
        }
        return $content;
    }

    //  生成随机的5个数字
    private function randomCode($len = 5) {
        $arr = [];
        while (count($arr) < $len) {
            $arr[] = rand(1, 10);
            $arr   = array_unique($arr);
        }
        return implode('', $arr);
    }

    // 获取验证码
    public function getValidateCode() {
        // https://help.aliyun.com/knowledge_detail/57717.html?spm=5176.doc55284.2.9.sy56SK 详情code
        $data = ['state' => 'error', 'msg' => '操作失败'];
        if ($this->request->isPost()) {
            $code  = $this->randomCode();
            $phone = input('post.phone');
            $type  = 0;
            if (input('?post.type')) {
                $type = $this->request->post('type');
            }
            if ($type) {
                $user = Db::name('users')->where('phone', $phone)->field('id')->find();
                if (is_null($user)) {
                    return json(['state' => 'error', 'msg' => '手机号未注册,可以点击注册按钮进行注册']);
                }
            }
            $res = $this->sendSms($phone, $code);
            $msg = $res['Code'];
            if (strlen($phone) != 11) {
                $data = ['state' => 'error', 'msg' => '手机号不正确，请输入正确手机号'];
            } elseif ($msg == 'OK') {
                //  验证码已经发送成功
                $resCode = Db::name('verify_code')->where('phone', $phone)->field('id,result')->find();
                if (is_null($resCode)) {
                    Db::name('verify_code')->insert([
                        'phone' => $phone,
                        'add_time' => time(),
                        'code' => $code,
                        'result'=> $msg,
                    ]);
                } else {
                    Db::name('verify_code')->where('phone', $phone)->update([
                        'code' => $code, 'update_time' => time(),'result' => $msg.'|'.$resCode['result']
                    ]);
                }
                $data = ['state' => 'success', 'msg' => '验证码已发送,请注意查收!30分钟内有效.'];
            } elseif ($msg == 'isv.BUSINESS_LIMIT_CONTROL') {
                //  今日发送次数已经用完
                $data = ['state' => 'error', 'msg' => '进入验证码发送次数已使用完.'];
            } elseif ($msg == 'isv.OUT_OF_SERVICE') {
                // 请联系客服处理
                $data = ['state' => 'error', 'msg' => '验证码发送失败,请联系客服.'];
            } elseif ($msg == 'isv.MOBILE_NUMBER_ILLEGAL') {
                // 手机号不正确
                $data = ['state' => 'error', 'msg' => '手机号不正确，请输入正确手机号.'];
            }
        } else {
            $data = ['state' => 'error', 'msg' => '操作失败'];
        }
        return json($data);
    }

    //  验证用户输入的验证码是否正确
    public function validateInputCode() {
        if ($this->request->isPost()) {
            $phone     = input('post.phone');
            $inputCode = input('post.code/d');
            $type      = 0;
            if (input('?post.type')) {
                $type = $this->request->post('type');
            }
            if (strlen($phone) != 11) {
                $data = ['state' => 'error', 'msg' => '手机号不正确，请输入正确手机号'];
            } else if (strlen($inputCode) < 3) {
                $data = ['state' => 'error', 'msg' => '验证码不正确，请输入正确的验证码'];
            } else {
                //$sendCode=cache("code_{$phone}");//已经发送的验证码 不存在返回false对于empty也是空
                $sendCode = Db::name('verify_code')->where('phone', $phone)->field('code')->find();
                $code     = $sendCode['code'];
                if (is_null($sendCode)) {
                    $data = ['state' => 'error', 'msg' => '请获取验证码'];
                } elseif ($code == $inputCode) {
                    if ($type) {
                        $user = Db::name('users')->where('phone', $phone)->field('id')->find();
                        if (is_null($user)) {
                            $data = ['state' => 'success', 'msg' => '手机号未注册'];
                        } else {
                            cookie('userId', $user['id']);
                            $data = ['state' => 'success', 'msg' => '登录成功'];
                        }
                    } else {
                        $data = ['state' => 'success', 'msg' => '验证码输入正确'];
                    }
                } else {
                    $data = ['state' => 'error', 'msg' => '验证码不正确'];
                }
            }
        } else {
            $data = ['state' => 'error', 'msg' => '操作失败'];
        }
        return json($data);
    }
    // 有人匹配了你的订单
    public function sellTip(){
        $phone=input('post.phone');
        return $this->sendSms($phone,0,'SMS_171850178');
    }
    // 交易完成
    public function orderSuccess(){
        $phone=input('post.phone');
        return $this->sendSms($phone,0,'SMS_171850184');
    }
}
